package com.fragrance.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fragrance.service.DeviceMainService;
import com.fragrance.service.UserDeviceBindService;
import com.fragrance.service.impl.DeviceMainServiceImpl;
import com.fragrance.service.impl.UserDeviceBindServiceImpl;
import com.fragrance.util.Constants;
import com.fragrance.util.ExcelUtil;
import com.jfinal.core.Controller;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.upload.UploadFile;

public class DeviceController  extends Controller {

	private Logger logger = LoggerFactory.getLogger(DeviceController.class);

	private DeviceMainService deviceService = new DeviceMainServiceImpl();
	
	private UserDeviceBindService userDeviceBindService = new UserDeviceBindServiceImpl();

	public void deviceAdd() {
		logger.info("-- begin DeviceController.deviceAdd========================");
		//获取用户信息
		String userInfo = Redis.use("users").get(getPara("token"));
		JSONObject userInfoJson = JSONObject.parseObject(userInfo);

		Map<String, Object> resultMap = null;
		String simNo = getPara("simNo");
		String IMEI = getPara("IMEI");
		String deviceStatus = getPara("deviceStatus");
		String rightStatus = getPara("rightStatus");
		String location  = getPara("location");
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("simNo", simNo);
			params.put("IMEI", IMEI);
			params.put("deviceStatus", deviceStatus);
			params.put("rightStatus", rightStatus);
			params.put("location", location);
			params.put("userId", userInfoJson.get("id"));
			logger.info("-- in DeviceController.deviceAdd,params{}",params);
			resultMap = deviceService.deviceAdd(params);
		} catch (Exception e) {
			logger.error("-- error DeviceController.deviceAdd,Exception{}",e);
			resultMap.put("code", Constants.ERROR_CODE);
			resultMap.put("msg", Constants.ERROR_MSG);
		}
		renderJson(resultMap);
	}

	public void deviceEdit() {
		logger.info("-- begin DeviceController.deviceEdit========================");
		//获取用户信息
		String userInfo = Redis.use("users").get(getPara("token"));
		JSONObject userInfoJson = JSONObject.parseObject(userInfo);

		Map<String, Object> resultMap = null;
		String deviceId = getPara("deviceId");
		String simNo = getPara("simNo");
		String IMEI = getPara("IMEI");
		String deviceStatus = getPara("deviceStatus");
		String rightStatus = getPara("rightStatus");
		String location  = getPara("location");
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("deviceId", deviceId);
			params.put("simNo", simNo);
			params.put("IMEI", IMEI);
			params.put("deviceStatus", deviceStatus);
			params.put("rightStatus", rightStatus);
			params.put("location", location);
			params.put("userId", userInfoJson.get("id"));
			logger.info("-- in DeviceController.deviceEdit,params{}",params);
			resultMap = deviceService.deviceEdit(params);
		} catch (Exception e) {
			logger.error("-- error DeviceController.deviceEdit,Exception{}",e);
			resultMap.put("code", Constants.ERROR_CODE);
			resultMap.put("msg", Constants.ERROR_MSG);
		}
		renderJson(resultMap);
	}

	public void deviceDelete() {
		logger.info("-- begin DeviceController.deviceDelete========================");
		Map<String, Object> resultMap = null;
		String deviceId = getPara("deviceId");
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("deviceId", deviceId);
			logger.info("-- in DeviceController.deviceDelete,params{}",params);
			resultMap = deviceService.deviceDelete(params);
		} catch (Exception e) {
			logger.error("-- error DeviceController.deviceDelete,Exception{}",e);
			resultMap.put("code", Constants.ERROR_CODE);
			resultMap.put("msg", Constants.ERROR_MSG);
		}
		renderJson(resultMap);
	}

	/**
	 * 设备列表
	 * /web/api/inner/device/deviceList
	 */
	public void deviceList() {
		logger.info("-- begin DeviceController.deviceList========================");
		Map<String, Object> resultMap = null;
		String simNo = getPara("simNo");
		String IMEI = getPara("IMEI");
		String deviceStatus = getPara("deviceStatus");
		String rightStatus = getPara("rightStatus");
		String pageNum = getPara("pageNum");
		String pageSize = getPara("pageSize");
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("simNo", simNo);
			params.put("IMEI", IMEI);
			params.put("deviceStatus", deviceStatus);
			params.put("rightStatus", rightStatus);
			params.put("pageNum", StringUtils.isNotBlank(pageNum)?pageNum:"1");
			params.put("pageSize", StringUtils.isNotBlank(pageSize)?pageSize:"20");
			logger.info("-- in DeviceController.deviceList,params{}",params);
			resultMap = deviceService.deviceList(params);
		} catch (Exception e) {
			logger.error("-- error DeviceController.deviceList,Exception{}",e);
			resultMap.put("code", Constants.ERROR_CODE);
			resultMap.put("msg", Constants.ERROR_MSG);
		}
		renderJson(resultMap);
	}

	public void deviceDetail() {
		logger.info("-- begin DeviceController.deviceDetail========================");
		Map<String, Object> resultMap = null;
		String deviceId = getPara("deviceId");
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("deviceId", deviceId);
			logger.info("-- in DeviceController.deviceDetail,params{}",params);
			resultMap = deviceService.deviceDetail(params);
		} catch (Exception e) {
			logger.error("-- error DeviceController.deviceDetail,Exception{}",e);
			resultMap.put("code", Constants.ERROR_CODE);
			resultMap.put("msg", Constants.ERROR_MSG);
		}
		renderJson(resultMap);
	}

	public void deviceWorkList() {
		logger.info("-- begin DeviceController.deviceWorkList========================");
		Map<String, Object> resultMap = null;
		String simNo = getPara("simNo");
		String IMEI = getPara("IMEI");
		String pageNum = getPara("pageNum");
		String pageSize = getPara("pageSize");
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("simNo", simNo);
			params.put("IMEI", IMEI);
			params.put("pageNum", pageNum);
			params.put("pageSize", pageSize);
			logger.info("-- in DeviceController.deviceWorkList,params{}",params);
			resultMap = deviceService.deviceWorkList(params);
		} catch (Exception e) {
			logger.error("-- error DeviceController.deviceWorkList,Exception{}",e);
			resultMap.put("code", Constants.ERROR_CODE);
			resultMap.put("msg", Constants.ERROR_MSG);
		}
		renderJson(resultMap);
	}

	public void deviceOprate(){
		logger.info("-- begin DeviceController.deviceOprate========================");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String deviceId = getPara("deviceId");
		String IMEI = getPara("IMEI");
		String rightStatus = getPara("rightStatus");
		logger.info("权限状态参数"+rightStatus);
		
		if("0".equals(rightStatus)){
			rightStatus = "1";
		}else{
			rightStatus = "0";
		}
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("deviceId", deviceId);
			params.put("IMEI", IMEI);
			params.put("rightStatus", rightStatus);
			logger.info("-- in DeviceController.deviceOprate,params{}",params);
			resultMap = deviceService.deviceOprate(params);
		} catch (Exception e) {
			logger.error("-- error DeviceController.deviceOprate,Exception{}",e);
			resultMap.put("code", Constants.ERROR_CODE);
			resultMap.put("msg", Constants.ERROR_MSG);
		}
		renderJson(resultMap);
	}
	
	//批量添加设备
	public void addDeviceByExcle(){
		logger.info("-- begin DeviceController.addDeviceByExcle========================");
		InputStream is = null;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Cache cache = Redis.use("users");
			logger.info("users cache: " + cache);
			if(cache == null){
				resultMap.put("code", "000005");
				resultMap.put("msg", "获取不到登录信息");
				renderJson(resultMap);
				return;
			}
			String token = getPara("token");
			if(StringUtils.isBlank(token)){
				resultMap.put("code", "000005");
				resultMap.put("msg", "获取不到token");
				renderJson(resultMap);
				return;
			}
			//获取用户信息
			String userInfo = Redis.use("users").get(token);
			JSONObject userInfoJson = JSONObject.parseObject(userInfo);
			logger.info("userInfo = " + userInfo);
			
			UploadFile uploadFile = getFile();
			if(null == uploadFile){
				resultMap.put("code","000001");
				resultMap.put("msg", "上传的excle文件为空");
			}else if(uploadFile != null && uploadFile.getFile().length() > 10*1024*1024){
				resultMap.put("code","000002");
				resultMap.put("msg", "上传的excle文件不能超过10M");
			}else{
				String fileName=uploadFile.getOriginalFileName();
				String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
				logger.info("===============上传文件的后缀名==========="+prefix);
				if(!"xlsx".equals(prefix.toLowerCase()) && !"xls".equals(prefix.toLowerCase())){
					resultMap.put("code", 000005);
					resultMap.put("msg", "上传的excle格式不正确，请下载网站提供的excle模板");
				}else{
					File file = uploadFile.getFile();
					is = new FileInputStream(file);
					List<List<String[]>> list = ExcelUtil.readExcel_xlsx(is);
					if(list==null||list.size() <= 0){
						resultMap.put("code", "000005");
						resultMap.put("msg", "excels数据为空或者无法解析excel");
					}else{
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("list", list);
						map.put("userId", userInfoJson.get("id"));
						logger.info("-- in DeviceController.addDeviceByExcel,params{}",map);
						resultMap = deviceService.addDeviceByExcel(map);
					}
				}
			} 
		}catch (FileNotFoundException e) {
			logger.error("找不到文件: ", e);
			resultMap.put("code", "000005");
			resultMap.put("msg", "找不到文件");
		} catch (IOException e) {
			logger.error("请上传正确格式的excel: ", e);
			resultMap.put("code", "000005");
			resultMap.put("msg", "请上传正确格式的excel");
		} catch (Exception e) {
			logger.error("系统繁忙请稍后再试: ", e);
			resultMap.put("code", "000005");
			resultMap.put("msg", "系统繁忙，请稍后再试！");
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}
		renderJson(resultMap);
	}
	
	//设备绑定权限
	public void deviceBindRight(){
		logger.info("-- begin DeviceController.deviceBindRight========================");
		//传入设备的imei号
		Map<String, Object> resultMap = null;
		String IMEI = getPara("IMEI");
		String remark1 = getPara("remark1");
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("IMEI", IMEI);
			params.put("remark1", remark1);
			logger.info("-- in DeviceController.deviceBindRight,params{}",params);
			resultMap = deviceService.deviceBindRight(params);
		} catch (Exception e) {
			logger.error("-- error DeviceController.deviceBindRight,Exception{}",e);
			resultMap.put("code", Constants.ERROR_CODE);
			resultMap.put("msg", Constants.ERROR_MSG);
		}
		renderJson(resultMap);
	}
	
	//设备绑定列表
	public void deviceBindList(){
		logger.info("-- begin DeviceController.deviceBindList========================");
		//传入设备的imei号
		Map<String, Object> resultMap = null;
		String IMEI = getPara("IMEI");
		String pageNum = getPara("pageNum");
		String pageSize = getPara("pageSize");
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("IMEI", IMEI);
			params.put("pageNum", StringUtils.isNotBlank(pageNum)?pageNum:"1");
			params.put("pageSize", StringUtils.isNotBlank(pageSize)?pageSize:"20");
			logger.info("-- in DeviceController.deviceBindList,params{}",params);
			resultMap = userDeviceBindService.deviceBindList(params);
			logger.info("-- in DeviceController.deviceBindList,resultMap{}",resultMap);
		} catch (Exception e) {
			logger.error("-- error DeviceController.deviceBindList,Exception{}",e);
			resultMap.put("code", Constants.ERROR_CODE);
			resultMap.put("msg", Constants.ERROR_MSG);
		}
		renderJson(resultMap);
	}
	
	//解除绑定设备
	public void deviceBindUntie(){
		// 传入设备的imei号
		Map<String, Object> resultMap = null;
		String IMEI = getPara("IMEI");
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("IMEI", IMEI);
			logger.info("-- in DeviceController.deviceBindUntie,params{}",params);
			resultMap = userDeviceBindService.deviceBindUntie(params);
		} catch (Exception e) {
			logger.error("-- error DeviceController.deviceBindUntie,Exception{}",e);
			resultMap.put("code", Constants.ERROR_CODE);
			resultMap.put("msg", Constants.ERROR_MSG);
		}
		renderJson(resultMap);
	}

	public void downfile() {//文件下载
		File file = new File("/usr/www/work/html/DEVICEINFO.xlsx");
		//本地的一张图片
		if (file.exists()) { //如果文件存在
			renderFile(file);
		} else {
			renderJson();
		}
	}
}
